package snbc.com.ContentProvoder;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import snbc.com.runtimepermissiontest.R;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class ContentResolver extends AppCompatActivity {
    private ListView lv_contacts;
    List<String> contacts = new ArrayList<>();
    ArrayAdapter<String> arrayAdapter;
    private TextView total;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_resolver);
        findView();
        //设置arrayAdapter适配器
        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, contacts);
        lv_contacts.setAdapter(arrayAdapter);
        //判断是否有获取通讯录权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            //无权限，向用户申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        } else {
            readContacts();//有权限直接读取联系人
        }
        Toast.makeText(this, "总共：" + contacts.size() + "位联系人", Toast.LENGTH_LONG).show();
        total.setText(contacts.size() + "");
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void readContacts() {
        Cursor cursor = null;
        //查询联系人
        try {
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    //获取联系人姓名
                    String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    //获取联系人手机号码
                    String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    //向list集合中装填数据
                    contacts.add(name + "\n" + phone);
                }
                arrayAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private void findView() {
        lv_contacts = findViewById(R.id.lv_contacts);
        total = findViewById(R.id.total);
    }

    //onRequestPermissionsResult回调方法中，判断。
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContacts();
                    Toast.makeText(this, "总共：" + contacts.size() + "位联系人", Toast.LENGTH_LONG).show();
                    total.setText(contacts.size() + "");
                } else {
                    Toast.makeText(this, "You denied the permission", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }
}
